/*
 * Created on 2005-10-20
 *
 */
package com.yl.cap.analyst.work.job;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.quartz.Trigger;
import org.springframework.context.ApplicationContext;

import com.yl.cap.analyst.config.ContextBean;
import com.yl.cap.analyst.work.dao.JobTaskDAO;
import com.yl.cap.analyst.work.domain.JobLog;
import com.yl.cap.analyst.work.domain.TaskLog;
import com.yl.cap.analyst.work.domain.TriggerCollection;
import com.yl.cap.analyst.work.task.Task;

public class CreateReportThread implements Runnable
{
    private String triggerName;

    /**
     * @return Returns the triggerName.
     */
    public String getTriggerName()
    {
        return triggerName;
    }

    /**
     * @param triggerName The triggerName to set.
     */
    public void setTriggerName(String triggerName)
    {
        this.triggerName = triggerName;
    }

    public void run()
    {
        Map jobMap = TriggerCollection.jobMap;
        Task task = null;
        if (jobMap == null || jobMap.size()==0)
        {
            return;
        }
        ApplicationContext context = ContextBean.springContext;
        TriggerCollection triggerCollection = (TriggerCollection) context
                .getBean("triggerCollection");
        for (int i = 0; i < triggerCollection.getTigerList().size(); i++)
        {
            if (((Trigger) triggerCollection.getTigerList().get(i)).getName()
                    .equals(triggerName));
            {
                if (!((Boolean) triggerCollection.getTigerState().get(i))
                        .booleanValue())
                {
                    return;
                }
            }
        }
        List taskList = (List) jobMap.get(triggerName);
        JobTaskDAO dao = (JobTaskDAO) context.getBean("jobTaskDAO");
        JobLog jobLog = new JobLog();
        TaskLog tmpTaskLog = null;

        if (taskList != null)
        {
            // record job log
            jobLog.setBeginTime(new Date());
            jobLog.setTigerName(triggerName);
            jobLog.setTaskCount(new Integer(taskList.size()));
            jobLog.setCompletedCount(new Integer(0));
            dao.saveEntity(jobLog);

            for (int i = 0; i < taskList.size(); i++)
            {
                task = (Task) taskList.get(i);
                tmpTaskLog = task.doTask(jobLog);
                tmpTaskLog.setJobLog(jobLog);
                dao.saveEntity(tmpTaskLog);
                jobLog.setCompletedCount(new Integer(i + 1));
                dao.updateEntity(jobLog);
            }
            taskList.clear();
        }
        // record job log
        jobLog.setEndTime(new Date());
        if (jobLog.getId() == null)
        {
            dao.saveEntity(jobLog);
        }
        else
        {
            dao.updateEntity(jobLog);
        }
    }
}
